package com.wan37.client.service;

import com.wan37.protobuf.message.client2server.game.GameEntity;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 延迟线程池工具
 *
 * @author : luoyong
 * @date : 2020-06-10 17:21
 **/
public class DelayThreadPool {

    /**
     * 延迟线程池
     */
    public final static ScheduledExecutorService poll = new ScheduledThreadPoolExecutor(10);

    /**
     * 初始化的插入，延迟时间为0，直接将技能全部放入
     *
     * @param allRoleId
     * @param skill
     */
    public static void initAdd(String allRoleId, GameEntity.Skill skill) {
        add(allRoleId, skill, 0);
    }

    /**
     * 通过技能CD时间之后的插入技能优先级别队列
     *
     * @param allRoleId
     * @param skill
     */
    public static void add(String allRoleId, GameEntity.Skill skill) {
        add(allRoleId, skill, (long) skill.getCD() + skill.getReading());
    }

    /**
     * 提交任务
     *
     * @param allRoleId
     * @param skill
     * @param delay
     */
    public static void add(String allRoleId, GameEntity.Skill skill, long delay) {
        /**
         * 可释放的优先级别队列里面没有技能则在延迟时间之后插入技能
         */
        if (!SkillService.allRoleIdToPBQMap.get(allRoleId).contains(skill)) {
            poll.schedule(() -> {
                SkillService.addPbqSkill(allRoleId, skill);
            }, delay, TimeUnit.SECONDS);
        }
    }

    public static void schedule(Runnable runnable, long delay){
        poll.schedule(runnable, delay, TimeUnit.SECONDS);
    }
}
